package com.laobiao.file_netty_lib.packet.command;

import java.nio.ByteBuffer;

import com.laobiao.file_netty_lib.exception.FileBaseException;
import com.laobiao.file_netty_lib.packet.BasePacket;
import com.laobiao.file_netty_lib.packet.PacketType;
import com.laobiao.file_netty_lib.util.BinaryConvertUtil;
/**
 * 命令包，第一个字节值为0
 * @author 38079
 *
 */
public abstract class BaseCommandPacket extends BasePacket{
	/**
	 * 命令类型
	 */
	private PacketCommandType command;


	public BaseCommandPacket() {
		setPacketType(PacketType.COMMAND);
	}
	public PacketCommandType getCommand() {
		return command;
	}

	public void setCommand(PacketCommandType command) {
		if(command==null) {
			throw new FileBaseException("命令类型不能为空！", FileBaseException.ERR_PARAM_NULL);
		}
		this.command = command;
	}

	
	/**
	 * 取命令内容字节数组
	 * 命令长度1014
	 * @return
	 */
	protected abstract byte[] getCommContentBytes() ;
	/**
	 *  取命令流转类型
	 */
	public abstract CommandCirculationType circulationType();
	
	/**
	 * 设置基础命令参数，包括命令类型
	 * @param commandBytes 命令包字节数组
	 * @return ByteBuffer 字节数组缓冲区，读指针指向命令类型内容区
	 */
	protected ByteBuffer setBaseCommand(byte[] commandBytes) {
//		setPacketType(judgePacketType(commandBytes));
//		setPacketType(PacketType.COMMAND);
		ByteBuffer buf=ByteBuffer.wrap(commandBytes);
//		buf.flip();
		setPacketType(PacketType.instance((int)buf.get()));//包类型
		setCommand(PacketCommandType.instance((int)buf.get()));//命令类型
		//取业务组编码
		byte[] chunk=new byte[4];
		buf.get(chunk);
		setBusinessGroup(BinaryConvertUtil.byteArrayToInt(chunk));
		return buf;
	}
	
	@Override
	public byte[] getPacketBytes() {
//		getPacketType().getType()
		ByteBuffer buf=ByteBuffer.allocate(1024);
		buf.put(BinaryConvertUtil.intToByte(getPacketType().getType()));//包类型
		buf.put(BinaryConvertUtil.intToByte(command.getCommand()));//命令类型
		buf.put(BinaryConvertUtil.intToByteArray(getBusinessGroup()));//业务组编号
		byte [] commBytes=getCommContentBytes();//命令内容
		if(commBytes.length!=1014) {
			throw new FileBaseException("命令内容错误！", FileBaseException.ERR_PARAM_WRONG);
		}
		buf.put(commBytes);
		return buf.array();
	}
	
	
}
